package com.it.hanzhongtravelv1.controller;

import com.it.hanzhongtravelv1.entity.Attraction;
import com.it.hanzhongtravelv1.service.AttractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/api/v1/attractions")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:8080"})
public class AttractionController {

    @Autowired
    private AttractionService attractionService;

    // 获取所有景点
    @GetMapping
    public List<Attraction> getAllAttractions() {
        return attractionService.findAll();
    }

    // 根据ID获取单个景点
    @GetMapping("/{id}")
    public ResponseEntity<Attraction> getAttractionById(@PathVariable Long id) {
        return attractionService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 新增一个景点
    @PostMapping
    public ResponseEntity<Attraction> createAttraction(@RequestBody Attraction attraction) {
        Attraction savedAttraction = attractionService.save(attraction);
        return ResponseEntity.created(URI.create("/api/v1/attractions/" + savedAttraction.getId())).body(savedAttraction);
    }

    // 根据ID更新一个景点
    @PutMapping("/{id}")
    public ResponseEntity<Attraction> updateAttraction(@PathVariable Long id, @RequestBody Attraction attractionDetails) {
        return attractionService.findById(id)
                .map(existingAttraction -> {
                    existingAttraction.setName(attractionDetails.getName());
                    existingAttraction.setDescription(attractionDetails.getDescription());
                    existingAttraction.setImage(attractionDetails.getImage());
                    existingAttraction.setLocation(attractionDetails.getLocation());
                    existingAttraction.setCategory(attractionDetails.getCategory());
                    existingAttraction.setRating(attractionDetails.getRating());
                    existingAttraction.setTicketPrice(attractionDetails.getTicketPrice());
                    existingAttraction.setOpenTime(attractionDetails.getOpenTime());
                    Attraction updatedAttraction = attractionService.save(existingAttraction);
                    return ResponseEntity.ok(updatedAttraction);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    // 根据ID删除一个景点
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAttraction(@PathVariable Long id) {
        return attractionService.findById(id)
                .map(attraction -> {
                    attractionService.deleteById(id);
                    return ResponseEntity.ok().<Void>build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
} 